﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.View;
using StyleMVVM.View.Regions;
#if NETFX_CORE
using Windows.UI.Xaml;

#endif

namespace StyleMVVM.ViewModel
{
	/// <summary>
	/// This is a base ViewModel designed to handle Region navigation. This is inlu 
	/// </summary>
	public class RegionAwareViewModel : NavigatingViewModel, IRegionAware
	{
		private WeakReference regionReference;

		/// <summary>
		/// This is the current region for the ViewModel. 
		/// It is held as a Weak reference so I do not recommend holding a strong reference to it
		/// That includes data binding.
		/// </summary>
		public IRegion Region
		{
			get
			{
				IRegion returnValue = null;

				if (regionReference != null)
				{
					returnValue = regionReference.Target as IRegion;
				}

				return returnValue;
			}
			set
			{
				if (value != null)
				{
					if (regionReference != null)
					{
						IRegion oldValue = regionReference.Target as IRegion;

						if (oldValue != null)
						{
							oldValue.PropertyChanged -= ValueOnPropertyChanged;
						}
					}

					// PropertyChanged is implemented as a Weak Event 
					value.PropertyChanged += ValueOnPropertyChanged;

					regionReference = new WeakReference(value);
				}
				else
				{
					regionReference = null;
				}
			}
		}

		public bool CanGoForward
		{
			get
			{
				IRegion region = Region;

				if (region != null)
				{
					return Region.CanGoForward;
				}

				return false;
			}
		}

		public bool CanGoBack
		{
			get
			{
				IRegion region = Region;

				if (region != null)
				{
					return Region.CanGoBack;
				}

				return false;
			}
		}

		public void GoForward()
		{
			IRegion region = Region;

			if (region != null)
			{
				region.GoForward();
			}
		}

		public void GoBack()
		{
			IRegion region = Region;

			if (region != null)
			{
				region.GoBack();
			}
		}

		public void GoHome()
		{
			IRegion region = Region;

			if (region != null)
			{
				region.GoHome();
			}
		}

		private void ValueOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
		{
			if (propertyChangedEventArgs.PropertyName == "CanGoBack")
			{
				OnCanGoBackChanged();
			}
			else if (propertyChangedEventArgs.PropertyName == "CanGoForward")
			{
				OnCanGoForwardChanged();
			}
		}

		protected virtual void OnCanGoBackChanged()
		{
			OnPropertyChanged("CanGoBack");
		}

		protected virtual void OnCanGoForwardChanged()
		{
			OnPropertyChanged("CanGoForward");
		}
	}
}